//
//  ViewController.m
//  NaviTwo
//
//  Created by apple on 16/2/29.
//  Copyright © 2016年 ZR. All rights reserved.
//

#import "ViewController.h"
#import "SecondViewController.h"
#import <AFNetworking.h>


@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic,strong) UIButton *userButton;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) NSString *fileName;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UINavigationBar *naviBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    naviBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:naviBar];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, naviBar.frame.size.width -30, 40)];
    
    UIButton *logoutButton = [UIButton  buttonWithType:UIButtonTypeSystem];
    logoutButton.frame = CGRectMake(view.bounds.size.width - 40, 0, 40, 30);
    [logoutButton setTitle:@"退出" forState:UIControlStateNormal];
    [view addSubview:logoutButton];
    
//    self.userButton = [UIButton  buttonWithType:UIButtonTypeSystem];
//    self.userButton.frame = CGRectMake(view.bounds.size.width - 80, 0, 40, 30);
//    [self.userButton setTitle:@"头像" forState:UIControlStateNormal];
//    [self.userButton addTarget:self action:@selector(chosePhoto) forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:self.userButton];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"user.png"]];
    imageView.frame = CGRectMake(view.bounds.size.width - 80, 0, 40, 30);
    [view addSubview:imageView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chosePhoto)];
    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:tap];
    self.imageView = imageView;
    
    
    UIButton *nameButton = [UIButton  buttonWithType:UIButtonTypeSystem];
    nameButton.frame = CGRectMake(0, 0, 40, 30);
    [nameButton setTitle:@"东风" forState:UIControlStateNormal];
    nameButton.enabled = NO;
    [view addSubview:nameButton];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = item;
    
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.navigationController pushViewController:[SecondViewController new] animated:YES];
        self.navigationController.navigationBar.hidden = NO;
}

//- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBar.hidden = YES;
//}

- (void)chosePhoto
{

    UIAlertController *alertVC = [[UIAlertController alloc]init];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
            imageVC.delegate = self;
            imageVC.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imageVC animated:YES completion:nil];
        } else {
            [alertVC addAction:[UIAlertAction actionWithTitle:@"相机不可用" style:UIAlertActionStyleDefault handler:nil]];
        }
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"本地上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
        imageVC.delegate = self;
        imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imageVC animated:YES completion:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }]];
    
    UIPopoverPresentationController *popPresenter = [alertVC
                                                     popoverPresentationController];
    popPresenter.sourceView = self.imageView;
    popPresenter.sourceRect = self.imageView.bounds;
    
    [self presentViewController:alertVC animated:YES completion:nil];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//    [_userButton setImage:info[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
//    [_userButton setTitle:@"" forState:UIControlStateNormal];
//    [self dismissViewControllerAnimated:YES completion:nil];
    self.imageView.image = info[UIImagePickerControllerOriginalImage];
    [self performSelector:@selector(saveImage:) withObject:self.imageView.image];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)saveImage:(UIImage *)image{
    
    NSData *imageData = UIImagePNGRepresentation(image);
    if(imageData == nil)
    {
        imageData = UIImageJPEGRepresentation(image, 1.0);
    }
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    _fileName = [[formatter stringFromDate:date] stringByAppendingPathExtension:@"png"];
//    NSLog(@"fileName:%@",_fileName);
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSLog(@"filePath:%@",filePath);
    NSURL *saveURL = [[NSURL URLWithString:filePath] URLByAppendingPathComponent:_fileName];
    [imageData writeToURL:saveURL atomically:YES];
    
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
//    NSString *file = [filePath stringByAppendingPathComponent:_fileName];
//    NSData *data = [NSData dataWithContentsOfFile:[filePath stringByAppendingPathComponent:_fileName]];
    NSLog(@"isExist:%i", isExist);
    
    

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
#warning 图片上传 服务器接口
    NSURL *url = [NSURL URLWithString:@"服务器接口"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:saveURL progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
   
    
    
//    SEL selectorToCall = @selector(imageWasSavedSuccessfully:didFinishSavingWithError:contextInfo:);
//    UIImageWriteToSavedPhotosAlbum(self.imageView.image, self,selectorToCall, NULL);

}

// 保存图片后到相册后，调用的相关方法，查看是否保存成功
//- (void) imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{
//    if (paramError == nil){
//        NSLog(@"Image was saved successfully.");
//    } else {
//        NSLog(@"An error happened while saving the image.");
//        NSLog(@"Error = %@", paramError);
//    }
//}
@end
